<template>
  <div class="create">
    <h3 class="title is-3">发布文章</h3>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left"  class="form">
      <el-form-item label="文章分类" prop="category">
    <!--    <el-input v-model="form.category" placeholder="请输入文章分类"></el-input>-->
        <el-radio-group v-model="form.category">
          <el-radio-button label="言情"></el-radio-button>
          <el-radio-button label="小说"></el-radio-button>
          <el-radio-button label="科技"></el-radio-button>
          <el-radio-button label="古文"></el-radio-button>
          <el-radio-button label="心灵鸡汤"></el-radio-button>
          <el-radio-button label="生活"></el-radio-button>
          <el-radio-button label="青春"></el-radio-button>
          <el-radio-button label="其它"></el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>

      <!--图片-->

      <div class="el-form-item is-required" :class="{ 'is-error': validate.error }" >
        <label class="el-form-item__label">上传图片</label>
          <qsj-pic-selected
            ref="picRef"
            :picWidth="width"
            :deviceVersions="deviceVersions"
            :oldimgs="imgs"
            :maxCount="9"></qsj-pic-selected>
        </div>
        <!--图片结束-->
      <div class="el-form-item is-required" :class="{ 'is-error': validate.error }">
        <label class="el-form-item__label">文章内容</label>
        <div class="el-form-item__content">
          <div id="editor"></div>
          <div v-if="validate.error" class="el-form-item__error">正文怎能没有内容呢？</div>
        </div>
      </div>

      <div class="oprator right">
        <el-button class="submit" type="primary" @click="submit" @keyup.enter="submit">发布文章</el-button>
      </div>

    </el-form>
  </div>
</template>

<script>

import { mapState } from 'vuex';
import qsjPicSelected from "@/components/qsjPicSelected"
import lrz from 'lrz'
let editor = null;

export default {

  name: 'create',

  data () {
    return {
     /* categorys: [],*/
      value:'',
      imgUrl:'',
      deviceVersions:'pc',
      imgs:[],
      newImgs:[],
      width:'10vw',
      form: {
        category: '',
        title: '',
        img:'',
      },
      rules: {
        title: [
          { required: true, message: "必须填写标题哦!", trigger: 'blur' },
        ],
        category: [
          { required: true, message: "必须填写分类哦!", trigger: 'blur' },
        ],

      },

      validate: {
        error: false
      }
    };
  },
  /*created(){
    this.getCategory();
  },*/
  mounted(){
    this.initEditor();
  },
  components:{
    qsjPicSelected
  },
  computed: mapState(['user']),
  methods: {
    /*图片*/
    addAvatar() {
      let that = this;
      lrz(event.currentTarget.files[0])
        .then(function (rst) {
          that.imgUrl = rst.base64;
          console.log("图片")
          console.log( that.imgUrl )
        })
        .catch(function (err) {
          this.$message.error('错了哦。');
        });
    },
    content(){
      return editor.$txt.html();
    },
    initEditor(){
      let E = window.wangEditor;
      editor = new E('editor')
      editor.config.menus = $.map(wangEditor.config.menus, function(item, key) {
          // https://www.kancloud.cn/wangfupeng/wangeditor2/113975 请看这里
          if (item === 'location') {
              return null;
          }
          return item;
      });

      editor.create();

      editor.onchange = () => {
        this.validateContent();
      }

    },
 /*   getCategory(){
      const cq = new this.$api.SDK.Query('Category');
      cq.find().then((categorys) => {
        this.categorys = categorys;
        console.log("分类")
        console.log(categorys)
        this.form.category = categorys[0];
        console.log(this.form.category)
        this.$Progress.finish();
      }).catch(console.error)
    },*/
    validateContent(){
      if (this.content() == '<p><br></p>') {
        this.validate.error = true;
        $('.wangEditor-container').css({borderColor:'red'})
        return false;
      }

      this.validate.error = false;
      $('.wangEditor-container').css({borderColor:'#ccc'})
      return true;
    },

    createArticle(){
      this.returnData = this.$refs.picRef.returnData();
      this.newImgs=this.$refs.picRef.returnData().newImgs;
      const article = new this.$api.SDK.Object('Article');
      article.set('author', this.user);
      article.set('title', this.form.title);
      article.set('content', this.content());
      article.set('category_name', this.form.category);
      article.set('article_img', this.newImgs);
      return article;
    },
    setACL(article){
      // 设置访问权限
      // https://leancloud.cn/docs/acl-guide.html#单用户权限设置
      let acl = new this.$api.SDK.ACL();
      acl.setPublicReadAccess(true);
      acl.setPublicWriteAccess(true);
      acl.setWriteAccess(this.user,true);
      article.setACL(acl);
    },
    save(article){
      article.save().then((article) => {
        console.log(article);
        const message =  `文章《${article.get('title')}》发布成功`;
        const status = new this.$api.SDK.Status();
        status.inboxType = 'friend';
        status.set('title', article.get('title'));
        status.set('type', 'create_article');
        status.set('article', article);

        this.$api.SDK.Status.sendStatusToFollowers(status).then((status) => {
          //发布状态成功，返回状态信息
          console.dir(status);
        }, (err) => {
          //发布失败
          console.dir(err);
        });
        this.$message({message, type: 'success'});
        this.$router.replace({name:"ArticleShow", params: { id: article.id }});
      }).catch(console.error);
    },

    submit(){
      this.$refs.form.validate((valid) => {
        const me = this.validateContent();
        if (valid && me) {
          const article = this.createArticle();
          this.setACL(article);
          this.save(article);
        } else {
          console.log('error submit!!');
          this.$message.error('错了哦，您填写的信息有错误，请按照提示修改。');
          return false;
        }
      })
    },
    /*图片*/

  },
};
</script>


<style lang="less" scoped>
/*.oprator{
  margin-top: 20px;
  float: right;
}
.title{
  text-align: center;
  font-family: '华文行楷';
}
.bg{
  backiground-color: #2c3e52;

}*/
  .create{
    width: 90%;
    margin: 0 auto;
    margin-top: 40px;
    text-align: center;
    .form{
      margin-top: 40px;
      text-align: left;
      #editor{
        height: 300px;
        overflow: scroll;
        overflow-x: hidden;
      }
      .el-button{
        background-color: #87CEFF;
        color: #ffffff;
      }
      .img{
        display: flex;
        align-items: center;
        flex-direction: row;
        .avatar-input{
          cursor: pointer;
          background-color: #cccccc;
        }
        .avatar{
          margin-left: 20px;
          display: inline-block;
          width: 70px;
          height: 70px;
          background-size: cover;
          border-radius: 50%;
        }
      }

    }
  }


</style>
